<?php

/**
 * @Author:      zwh
 * @DateTime:    2016-10-10 16:25:05
 * @Description: 业务提成
 */
class ScsBusinessCommissionController extends BaseController
{
    /**
     * @Author:      zwh
     * @DateTime:    2016-10-12 11:34:18
     * @Description: 创建业务提成项目
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'bc' => 'required',
                'order_id' => 'required',
                'order_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $bc=json_decode(Input::get('bc'),1);
            $order_id=Input::get('order_id');
            $order_type=Input::get('order_type');
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $response=DB::transaction(function () use ($bc,$sc_user,$order_id,$order_type) {
                foreach($bc as $_bc){
                    $bc=new BusinessCommission;
                    $bc->order_id=$order_id;
                    $bc->order_type=$order_type;
                    $bc->user_type=$_bc['user_type'];
                    $bc->user_id=$_bc['user_id'];
                    $bc->business_id=$_bc['business_id'];
                    $bc->amount=$_bc['amount']*100;
                    $bc->created_by=$sc_user->id;
                    $bc->status=1;
                    $bc->verify_status=0;
                    $bc->shop_id=$sc_user->shop_id;
                    $bc->save();
                }
                return  array('code' => 0, 'msg' => 'ok', 'result' => array());
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-10-12 11:46:30
     * @Description: 验证订单号
     */
    public function verification(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            $insurance=Insurance::find(Input::get('order_id'));
            $service=ServiceCardOrder::find(Input::get('order_id'));
            $allow_bi = BusinessItem::allow_bi($sc_user->shop_id);
            if(!is_null($orders)){
                if($orders->shop_id!=$sc_user->shop_id){
                    $response = Lang::get("scs_error.order_note_shop_error_40003");
                    break;
                }
                if(!in_array($orders->status,Orders::$complete)){//是否已结算
                    $response = Lang::get("scs_error.order_status_error_40027");
                    break;
                }

                $lists=BusinessItem::where('business_item.type',1)->where('business_item.status',1)->select('business_item.id','business_item.name',"business_item.desc")->whereIn("business_item.id",$allow_bi)->get();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_type"=>1,"list"=>$lists));
                break;
            }
            
            if(!is_null($insurance)){
                if($insurance->website!=$sc_user->shop_id){
                    $response = Lang::get("scs_error.insurance_shop_error_90007");
                    break;
                }
                if(!in_array($insurance->insurance_type,array(2,3))){
                    $response = Lang::get("scs_error.commercial_insurance_notexiet_90006");
                    break;
                }
                // $lists=BusinessItem::where('type',2)->where('status',1)->select('id','name',"desc")->get();
                $lists=BusinessItem::where('business_item.type',2)->where('business_item.status',1)->select('business_item.id','business_item.name',"business_item.desc")->whereIn("business_item.id",$allow_bi)->get();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_type"=>2,"list"=>$lists));
                break;
            }

            if(!is_null($service)){
                if($service->shop_id!=$sc_user->shop_id){
                    $response = Lang::get("scs_error.order_note_shop_error_40003");
                    break;
                }
                if($service->status!=1417){//是否已结算
                    $response = Lang::get("scs_error.order_status_error_40027");
                    break;
                }
                // $lists=BusinessItem::where('type',3)->where('status',1)->select('id','name',"desc")->get();
                $lists=BusinessItem::where('business_item.type',3)->where('business_item.status',1)->select('business_item.id','business_item.name',"business_item.desc")->whereIn("business_item.id",$allow_bi)->get();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_type"=>3,"list"=>$lists));
                break;
            }
            $response=Lang::get("scs_error.order_id_error_90008");
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "verification", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-10-10 16:27:07
     * @Description: 业务提成列表
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
            $bc=BusinessCommission::leftJoin('orders','orders.order_id',"=",'business_commission.order_id')
            ->leftJoin('return_order','return_order.order_id','=','orders.order_id')  
            ->leftJoin('business_item','business_item.id','=','business_commission.business_id')            
            // ->where('orders.shop_id',$sc_user->shop_id) 这个判断错误  业绩表加门店 加订单类型
            ->leftJoin('insurance','insurance.id','=','business_commission.order_id')
            ->leftJoin('service_card_order','service_card_order.order_id','=','business_commission.order_id')
            // ->where(function($query) use ($sc_user)
            // {
            //     $query->where('orders.shop_id',$sc_user->shop_id)
            //           ->orWhere('insurance.website',$sc_user->shop_id)
            //           ->orWhere('service_card_order.shop_id',$sc_user->shop_id);;
            // })
            ->where('business_commission.shop_id',$sc_user->shop_id)
            ->where('business_commission.status',1)
            ->orderBy('orders.pay_time');

            if(Input::get("verify_status")!=""){
                $bc=$bc->where("business_commission.verify_status",Input::get("verify_status"));
            }
            if(Input::get("order_id")!=""){
                $bc=$bc->where("business_commission.order_id",'like','%'.Input::get('order_id').'%');
            }
            if(Input::get("business_id")!=""){
                $bc=$bc->where("business_commission.business_id",Input::get("business_id"));
            }
            if(Input::get('user_type')!=""){
                $bc=$bc->where("business_commission.user_type",Input::get("user_type"));
            }
            if(Input::get('user_id')!=""){
                $bc=$bc->where("business_commission.user_id",Input::get("user_id"));
            }
            if(Input::get('pay_time')!=""){
                $it=Input::get('pay_time');
                $it=explode('~',$it);
                $start_time=$it[0].' 00:00:00';
                $end_time=$it[1].' 23:59:59';
                $start_time=date("Y-m-d H:i:s",strtotime($start_time));
                $end_time=date("Y-m-d H:i:s",strtotime($end_time));
                // $bc=$bc->where(function($query)use($start_time,$end_time)
                //     {
                //         $query->whereBetween("orders.pay_time",array($start_time,$end_time))
                //               ->orWhereBetween("insurance.created_at",array($start_time,$end_time))
                //               ->orWhereBetween("service_card_order.pay_time",array($start_time,$end_time));
                //     }

                // );
                $bc=$bc->whereBetween("business_commission.created_at",array($start_time,$end_time));
            }
            $count=$bc->count();
            $bc=$bc->skip($page_size*($page-1))->take($page_size)->select("business_commission.*","orders.order_type as otp","orders.pay_time","insurance.created_at as i_pay_time","service_card_order.pay_time as s_pay_time","return_order.id as return_order_id","business_item.name","business_item.type as b_type","business_item.desc","orders.payable_amount as o_amount"
                ,"orders.car_no as o_car_no"
                ,"insurance.amount as in_amount"
                ,"insurance.car_no as in_car_no"
                ,"service_card_order.pay_amount as se_amount"
                ,"service_card_order.car_no as se_car_no")->get();
            // Log::info(DB::getQueryLog());
            foreach($bc as $_bc){
                if($_bc->user_type==1){
                    $m=MaintenanceEngineers::find($_bc->user_id);
                    $_bc->user_name=$m->name;
                }else{
                    $s1=SCUser::find($_bc->user_id);
                    $_bc->user_name=$s1->real_name;
                }
                $s2=SCUser::find($_bc->created_by);
                $_bc->create_name=$s2->real_name;
                $_bc->amount=$_bc->amount/100;
                switch ($_bc->order_type) {
                    case '1':
                        break;
                    case '2':
                        $_bc->pay_time=$_bc->i_pay_time;
                        break;
                    case '3':
                        $_bc->pay_time=$_bc->s_pay_time;
                        break;                   
                }
            }
            $me=MaintenanceEngineers::where('type','shop')->where('type_id',$sc_user->shop_id)->where('status',1)->select('id','name')->get();
            $sc=SCUser::where('shop_id',$sc_user->shop_id)->where('status',1)->select('id','real_name')->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"bc"=>$bc,"me"=>$me,"sc"=>$sc));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-10-12 13:46:31
     * @Description: 审核
     */
    public function verify(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'ids' => 'required',
                'type' => 'required'
            )
        );
        $ids=json_decode(Input::get('ids'),1);
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $verify_status=BusinessCommission::whereIn('id',$ids)->select('verify_status')->get()->toArray();
            $verify_status=array_column($verify_status,'verify_status');
            if(Input::get('type')==1){
                $sc=SCUser::find(Input::get('id'));
                $area="010";
                $phone=$sc->phone;
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id',$ids[0])->where("business_type","business_commission")->where("phone",$phone)->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
            
                //校验验证码是否匹配
                if($record->check_code != Input::get('code')){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                $sc=SCUser::where('user_name',Input::get('account'))->where('password',strtoupper(md5(Input::get('passwd'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
            }
            $response=DB::transaction(function () use ($ids,$sc) {
                foreach($ids as $_id){
                    $bc=BusinessCommission::find($_id);
                    $bc->verify_time=date('Y-m-d H:i:s',time());
                    $bc->verify_status=1;
                    $bc->verify_user=$sc->id;
                    $bc->save();
                }
                return  array('code' => 0, 'msg' => 'ok', 'result' => '');
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "verify", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-9-23 17:37:39
     * @Description: 核销前判断
     */
    public function verifyBefore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'ids' => 'required',
            )
        );
        $ids=json_decode(Input::get('ids'),1);
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $verify_status=BusinessCommission::whereIn('id',$ids)->select('verify_status')->get()->toArray();
            $verify_status=array_column($verify_status,'verify_status');
            foreach($ids as $_id){
                if(in_array(1,$verify_status)){//如果 取消核销 报错
                    $response = Lang::get("scs_error.business_commission__error_90000");
                    $response["result"]=array("存在已核销项目");
                    break;
                }
            }
           
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelVerify", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-3 18:47:58
     * @Description: 发短信
     */
    public function verifyMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "id"=>'required',
                "ids"=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ids=json_decode(Input::get('ids'),1);
            $sc=SCUser::find(Input::get('id'));
            $phone=$sc->phone;
            $area='';
            $time_out_default = Config::get("user.time_out_default");
    
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::whereIn('business_id',$ids)->where("business_type","business_commission")->orderBy('out_time_at')->where("phone",$phone)->get();
            if($record->count()){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record[0]->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请核销业务，您的授权码为'.$record[0]->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record[0]->out_time_at) - time(),
                        ));
                    break;
                }else{ //超过限时
                    UserCheckCodeUpgrade::whereIn('business_id',$ids)->where("business_type","business_commission")->orderBy('out_time_at')->where("phone",$phone)->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area,$phone,'您好：'.$sc_user->shop->name.'，申请核销业务，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            $response=DB::transaction(function () use ($ids,$phone,$check_code,$time_out_default,$sms_send_record_id) {
                foreach($ids as $id){
                    $record = new UserCheckCodeUpgrade;
                    $record->business_type="business_commission";
                    $record->business_id=$id;
                    $record->phone=$phone;
                    $record->area="";
                    $record->check_code=$check_code;
                    $record->out_time_at=Common::num2DateTime(time() + $time_out_default);
                    $record->send_id=$sms_send_record_id;
                    $record->save();
                    //组织返回
                }
                $response = array(
                    'code' => 0,
                    'msg' => 'ok',
                    'result' => array(
                        'out_time' => $time_out_default,
                    ));
                return $response;
            });
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "verifyMessage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-10-12 11:50:12
     * @Description: 删除业务提成项
     */
    public function delete(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array());
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $bc=BusinessCommission::find(Input::get('id'));
            if(is_null($bc)){
                $response = Lang::get("scs_error.business_commission_notexiet_90001");
                break;
            }
            if($bc->verify_status==1){
                $response = Lang::get("scs_error.business_commission_delete_error_90002");
                break;
            }
            $bc->status=0;
            $bc->save();
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "delete", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-14 15:23:31
     * @Description: 所有计提项目
     */
    public function items(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array());
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $bi=BusinessItem::All();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('items'=>$bi));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "items", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}